package com.cyz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyz.dao.OldDao;
import com.cyz.dao.UserDao;
import com.cyz.entity.Doctor;
import com.cyz.entity.Old;
import com.cyz.entity.Old;
import com.cyz.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/old")
public class OldController {

    @Autowired
    private OldDao oldDao;

    @Autowired
    private UserDao userDao;

    @PostMapping("/query")
    public List<Old> queryOld(){
        List<Old> Olds = oldDao.selectList(new QueryWrapper<Old>());
        return Olds;
    }

    @PostMapping("/queryOldByCon")
    public List<Old> queryOldByCon(String id, String name, String job){
        QueryWrapper<Old> wrapper = new QueryWrapper<>();
        if (!id.equals("")){
            int i = Integer.parseInt(id);
            if (i > 0) {
                wrapper.eq("id",i);
            }
        }
        if (name != null && !name.equals("")){
            wrapper.eq("name", name);
        }
        if (job != null && !job.equals("")){
            wrapper.eq("tel", job);
        }
        List<Old> Olds = oldDao.selectList(wrapper);
        return Olds;
    }

    @PostMapping("/getOldId")
    public List<Integer> getDocId(){
        return oldDao.selectList(new QueryWrapper<Old>()).stream().map(item -> item.getId()).collect(Collectors.toList());
    }

    @PostMapping("/getOldById/{id}")
    public Old getDocById(@PathVariable int id){
        return oldDao.selectById(id);
    }

    @PostMapping("/updateOld")
    public String updateDoc(Old Old){
        System.out.println(Old.getId());
        System.out.println(Old.getName());
        int update = oldDao.update(Old, new QueryWrapper<Old>().eq("id", Old.getId()));
        return update == 0 ? "更新失败" : "更新成功";
    }

    @PostMapping("/deleteOld/{id}")
    public String deleteDoc(@PathVariable int id){
        Old Old = oldDao.selectById(id);
        int delete = oldDao.deleteById(id);
        if (delete != 0){
            String name = Old.getName();
            userDao.delete(new QueryWrapper<User>().eq("name",name));
        }
        return delete == 0 ? "删除失败" : "删除成功";
    }
}
